
#import "PullTableView.h"
#import "UIScrollView+SVInfiniteScrolling.h"

@implementation PullTableView

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)addRefreshAndLoadMore {
    UIView *view = [[UIView alloc] init];
    [self setTableFooterView:view];
    if ([self needRefreshView]) {   // 添加刷新控件
        [self addRefreshViewControl];
    }
    if ([self needLoadMoreView]) {  // 添加更多
        [self addInfiniteScrolling];
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];
    self.tableFooterView = [[UIView alloc] init];
    [self addRefreshAndLoadMore];
}

#pragma mark- RefreshLoadMoreDelegate

- (BOOL)needRefreshView {
    if (_pullDelegate && [_pullDelegate respondsToSelector:@selector(needRefreshView)]) {
        return [_pullDelegate needRefreshView];
    }
    return YES;
}

- (BOOL)needLoadMoreView {
    if (_pullDelegate && [_pullDelegate respondsToSelector:@selector(needLoadMoreView)]) {
        return [_pullDelegate needLoadMoreView];
    }
    return YES;
}

#pragma mark-   外部调用

- (void)setHasMore:(BOOL)hasMore {
    self.infiniteScrollingView.enabled = hasMore;
    self.infiniteScrollingView.state = hasMore ? SVInfiniteScrollingStateNormal : SVInfiniteScrollingStateNoMore;
}

- (void)didRefreshFinished {
    
}

- (void)didLoadMoreFinishedErrorWithFirst:(BOOL)isFirstRequest {
    if (isFirstRequest) {
        self.infiniteScrollingView.state = SVInfiniteScrollingStateFailAndHidden;
    } else {
        [self setHasMore:YES];
    }
}

#pragma mark - 内部调用

// 添加UIRefreshControl下拉刷新控件到UITableViewController的view中
- (void)addRefreshViewControl {
    
}

- (void)removeRefreshView {
    
}

- (void)setPullDelegeteToNil {
    self.showsInfiniteScrolling = NO;
    self.pullDelegate = nil;
}

#pragma mark - 上拉更多

// 添加加载更多控件
- (void)addInfiniteScrolling {
    __weak PullTableView *_self = self;
    [self addInfiniteScrollingWithActionHandler:^{
        [_self.pullDelegate loadData:LoadMore_req];
    }];
}

// 点击更多
- (void)onLoadMoreBtnClick {
    [self.pullDelegate loadData:LoadMore_req];
}

@end
